from datetime import datetime

from flask import request

from flask_jwt_extended import jwt_required
from flask_restx import Namespace, Resource, fields
from app1 import db

from app1.models import Zbfwbrole

# 创建 Flask-RESTx 命名空间
ns_role = Namespace('ns_role', description='Role operations')

# 使用 Flask-RESTx 定义用户数据模型
role_model = ns_role.model('Zbfwbrole', {
    'zbfwb_role_id': fields.Integer(readOnly=True, description='The role unique identifier'),
    'zbfwb_role_name': fields.String(required=True, description='Role name'),
    'zbfwb_role_title': fields.String(required=True, description='Role tittle'),
    'zbfwb_role_createtime': fields.DateTime(description='Role creation time'),
    'zbfwb_role_updatetime': fields.DateTime(description='Role update time')
})

# 定义外层的响应模型
response_role_model = ns_role.model('Response_Role', {
    'message': fields.Nested(ns_role.model('Message_Role', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.List(fields.Nested(role_model))
    }))
})

# 使用 Flask-RESTx 定义用户数据模型
role_query_model = ns_role.model('Zbfwbrole', {
    'zbfwb_role_id': fields.Integer(required=True, description='The role unique identifier'),
    'zbfwb_role_name': fields.String(required=True, description='Role name',default=""),
    'zbfwb_role_title': fields.String(required=True, description='Role tittle',default=""),
})

# 使用 Flask-RESTx 定义用户数据模型
role_add_model = ns_role.model('Zbfwbroleadd', {
    'zbfwb_role_name': fields.String(required=True, description='Role name',default=""),
    'zbfwb_role_title': fields.String(required=True, description='Role tittle',default=""),
})

# 使用 Flask-RESTx 定义用户数据模型
role_delete_model = ns_role.model('Zbfwbroledelete', {
    'zbfwb_role_name': fields.String(required=True, description='Role name',default=""),
})

# 使用 Flask-RESTx 定义用户数据模型
role_upd_model = ns_role.model('Zbfwbroleupd', {
    'zbfwb_role_name': fields.String(required=True, description='Role name',default=""),
    'zbfwb_role_title': fields.String(required=True, description='Role tittle',default=""),
})


# 查询
@ns_role.route('/role_list')
class RoleResource(Resource):
    # @jwt_required()
    @ns_role.expect(role_query_model)
    @ns_role.marshal_with(response_role_model)
    def post(self):
        """根据输入的id 或者 name 或者 title 匹配查询，如果输入值为空，则指匹配全部"""
        data = request.get_json()

        # 构建查询条件
        query = Zbfwbrole.query
        if 'zbfwb_role_id' in data and data['zbfwb_role_id']:
            query = query.filter_by(zbfwb_role_id=data['zbfwb_role_id'])
        if 'zbfwb_role_name' in data and data['zbfwb_role_name']:
            query = query.filter(Zbfwbrole.zbfwb_role_name.like(f"%{data['zbfwb_role_name']}%"))
        if 'zbfwb_role_title' in data and data['zbfwb_role_title']:
            query = query.filter(Zbfwbrole.zbfwb_role_title.like(f"%{data['zbfwb_role_title']}%"))

        roles = query.all()

        return {
            'message': {
                'result': 0,
                'result_text': '查询成功',
                'count': len(roles),
                'data': [role.to_dict() for role in roles]
            }
        }


# 新增
@ns_role.route('/role_create')
class RoleAddResource(Resource):
    # @jwt_required()
    @ns_role.expect(role_add_model)
    @ns_role.marshal_with(response_role_model)
    def post(self):
        """ id 为当前总记录加1，name 和 title 需要输入"""
        data = request.get_json()

        # 检查必填字段是否为空
        required_fields = ['zbfwb_role_name', 'zbfwb_role_title']
        missing_fields = [field for field in required_fields if not data.get(field)]

        if missing_fields:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'以下字段不能为空: {", ".join(missing_fields)}',
                    'count': 0,
                    'data': []
                }
            }, 400

        # 检查角色名是否已存在
        if Zbfwbrole.query.filter_by(zbfwb_role_name=data['zbfwb_role_name']).first():
            return {
                'message': {
                    'result': 1,
                    'result_text': f'角色名"{data["zbfwb_role_name"]}"已存在',
                    'count': 0,
                    'data': []
                }
            }, 400

        try:
            # 获取当前最大ID并加1
            max_id = db.session.query(db.func.max(Zbfwbrole.zbfwb_role_id)).scalar() or 0
            new_id = max_id + 1

            # 创建新角色
            new_role = Zbfwbrole(
                zbfwb_role_id=new_id,
                zbfwb_role_name=data['zbfwb_role_name'],
                zbfwb_role_title=data['zbfwb_role_title']
            )

            db.session.add(new_role)
            db.session.commit()

            return {
                'message': {
                    'result': 0,
                    'result_text': '角色创建成功',
                    'count': 1,
                    'data': [new_role.to_dict()]
                }
            }, 201
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'创建角色时发生错误: {str(e)}',
                    'count': 0,
                    'data': []
                }
            }, 500


# 删除
@ns_role.route('/role_delete')
class RoleDeleteResource(Resource):
    # @jwt_required()
    @ns_role.expect(role_delete_model)
    @ns_role.marshal_with(response_role_model)
    def post(self):
        """Delete a role"""
        data = request.get_json()

        # 查找要删除的角色
        role = Zbfwbrole.query.filter_by(zbfwb_role_name=data['zbfwb_role_name']).first()
        if not role:
            return {
                'message': {
                    'result': 1,
                    'result_text': '角色不存在',
                    'count': 0,
                    'data': []
                }
            }, 404

        db.session.delete(role)
        db.session.commit()

        return {
            'message': {
                'result': 0,
                'result_text': '角色删除成功',
                'count': 1,
                'data': [role.to_dict()]
            }
        }


# 修改
@ns_role.route('/role_updt')
class RoleUpdateResource(Resource):
    # @jwt_required()
    @ns_role.expect(role_upd_model)
    @ns_role.marshal_with(response_role_model)
    def post(self):
        """Update a role"""
        data = request.get_json()

        # 检查必填字段是否为空
        required_fields = ['zbfwb_role_name', 'zbfwb_role_title']
        missing_fields = [field for field in required_fields if not data.get(field)]

        if missing_fields:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'以下字段不能为空: {", ".join(missing_fields)}',
                    'count': 0,
                    'data': []
                }
            }, 400

        try:
            # 查找要更新的角色
            role = Zbfwbrole.query.filter_by(zbfwb_role_name=data['zbfwb_role_name']).first()
            if not role:
                return {
                    'message': {
                        'result': 1,
                        'result_text': '角色不存在',
                        'count': 0,
                        'data': []
                    }
                }, 404

            # 更新角色信息
            role.zbfwb_role_title = data['zbfwb_role_title']
            role.zbfwb_role_updatetime = datetime.utcnow()

            db.session.commit()

            return {
                'message': {
                    'result': 0,
                    'result_text': '角色更新成功',
                    'count': 1,
                    'data': [role.to_dict()]
                }
            }
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'更新角色时发生错误: {str(e)}',
                    'count': 0,
                    'data': []
                }
            }, 500
